package com.hxzy.shop.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.shop.entity.*;
import com.hxzy.shop.order.dto.req.OrderCountsReq;
import com.hxzy.shop.order.dto.req.OrderDetailReq;
import com.hxzy.shop.order.dto.req.OrderManageReq;
import com.hxzy.shop.order.dto.resp.*;
import com.hxzy.shop.order.feign.FreightFeign;
import com.hxzy.shop.order.mapper.*;
import com.hxzy.shop.order.service.OrderService;
import com.hxzy.shop.vo.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单操作
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderTableMapper orderTableMapper;

    @Resource
    private StoreMapper storeMapper;


    @Resource
    /*物流查询*/
    private FreightFeign freightFeign;

    @Resource
    /*药品信息*/
    private OrderInnerDrugMapper orderInnerDrugMapper;

    @Resource
    /*优惠劵信息*/
    private CouponMapper couponMapper;

    @Resource
    /*售后订单信息*/
    private OrderAfterSalesMapper orderAfterSalesMapper;

    @Resource
    private OrderDrugUsersMapper orderDrugUsersMapper;


    @Resource
    private GroupBookingInnerOrderMapper groupBookingInnerOrderMapper;


    /**
     * 订单列表
     *
     * @param orderManageReq 订单请求体
     * @return 订单分页
     */

    @Override
    public PageInfo<OrderManageListResp> getOrderManageList(OrderManageReq orderManageReq) {
        System.out.println("请求到impl---");
        PageInfo<OrderManageListResp> objectPageInfo = PageHelper.startPage(orderManageReq.getPageNumber(), orderManageReq.getPageSize())
                .doSelectPageInfo(() -> orderTableMapper.getOrderManageList(orderManageReq));

        List<OrderManageListResp> list = objectPageInfo.getList();
        List<OrderManageListResp> collect = list.stream().map(e -> {
            Integer isSponsor = e.getIsSponsor();
            Long sponsorId = e.getSponsorId();
            if (ObjectUtil.isNotEmpty(isSponsor) && ObjectUtil.isNotEmpty(sponsorId) && (orderManageReq.getOrderState() != 1 && orderManageReq.getOrderState() != 7)) {
                GroupBookingInnerOrder groupBookingInnerOrder = groupBookingInnerOrderMapper.selectOne(new LambdaQueryWrapper<GroupBookingInnerOrder>()
                        .eq(GroupBookingInnerOrder::getIsSponsor, true).eq(GroupBookingInnerOrder::getSponsorId, sponsorId));
                if (ObjectUtil.isNotEmpty(groupBookingInnerOrder)) {
                    e.setClusteringStatus(groupBookingInnerOrder.getClusteringStatus());
                }
            }
            return e;
        }).collect(Collectors.toList());
        objectPageInfo.setList(collect);
        return objectPageInfo;
    }

    /**
     * 获得所有门店
     *
     * @return 门店集合
     */
    @Override
    public List<StoreResp> getStoreList() {
        return storeMapper.selectList(new LambdaQueryWrapper<Store>()
          .select(Store::getId, Store::getStoreName)).stream().map(store ->
          new StoreResp(store.getId(), store.getStoreName())).collect(Collectors.toList());
    }

    /**
     * 获得订单列表总数
     *
     * @param orderCountsReq 请求体
     * @return 订单列表总数
     */
    @Override
    public OrderCountsResp orderCountS(OrderCountsReq orderCountsReq) {
        OrderCountsResp result = new OrderCountsResp();
        result.setTotalCount(orderTableMapper.orderCountTotal(orderCountsReq.getStoreId()));
        result.setPaymentOnBehalf(orderTableMapper.orderCountOnBehalf(orderCountsReq.getStoreId()));
        result.setConsignment(orderTableMapper.orderCountConsignments(orderCountsReq.getStoreId()));
        result.setPrepareGoodsBehalf(orderTableMapper.orderCountPrepareGoodsBehalf(orderCountsReq.getStoreId()));
        result.setCollectGoodsBehalf(orderTableMapper.orderCountCollectGoodsBehalf(orderCountsReq.getStoreId()));
        result.setToBeMentioned(orderTableMapper.orderCountToBeMentioned(orderCountsReq.getStoreId()));
        result.setCompleted(orderTableMapper.orderCountCompleted(orderCountsReq.getStoreId()));
        result.setClosed(orderTableMapper.orderCountClosed(orderCountsReq.getStoreId()));

        return result;
    }


    /**
     * 订单详细
     *
     * @param orderDetailReq 订单详情请求体
     * @return 订单详情
     */
    @Override
    public OrderDetailResp getOrderDetail(OrderDetailReq orderDetailReq) {
        // 订单基本信息
        OrderDetailResp orderDetailResp = orderTableMapper.getOrderDetail(orderDetailReq);
        //订单全称地址
        if (ObjectUtils.isEmpty(orderDetailResp)) {
            throw new ApiException(500, "订单不存在");
        }
        OrderTable orderTable = orderTableMapper.selectOne(new LambdaQueryWrapper<OrderTable>().select(OrderTable::getTotalPrice, OrderTable::getUserInnerCouponId).eq(OrderTable::getId, orderDetailReq.getOrderId()));
        orderDetailResp.setTotalPrice(orderTable.getTotalPrice());
        //药品信息
        List<OrderInnerDrug> orderInnerDrugList = orderInnerDrugMapper.selectList(new LambdaQueryWrapper<OrderInnerDrug>().eq(OrderInnerDrug::getOrderId, orderDetailResp.getId()));
        //设置优惠金额
        orderInnerDrugList = orderInnerDrugList.stream().map(orderInnerDrug -> {
            if (ObjectUtil.isEmpty(orderInnerDrug.getGift()) || orderInnerDrug.getGift() == 0) {
                BigDecimal memberRightsAmount = ObjectUtil.isNotEmpty(orderInnerDrug.getMemberRightsAmount()) ? orderInnerDrug.getMemberRightsAmount() : new BigDecimal(0);
                BigDecimal activityDiscountPrice = ObjectUtil.isNotEmpty(orderInnerDrug.getActivityDiscountPrice()) ? orderInnerDrug.getActivityDiscountPrice() : new BigDecimal(0);
                BigDecimal couponAllocationAmount = ObjectUtil.isNotEmpty(orderInnerDrug.getCouponAllocationAmount()) ? orderInnerDrug.getCouponAllocationAmount() : new BigDecimal(0);
                BigDecimal totalPrice = memberRightsAmount.add(activityDiscountPrice).add(couponAllocationAmount);
                orderInnerDrug.setTotalOffer(totalPrice.setScale(2, BigDecimal.ROUND_DOWN));
                orderInnerDrug.setGift(0);
            } else {
                orderInnerDrug.setOriginalPriceOfDrugs(BigDecimal.ZERO);
                orderInnerDrug.setTotalOffer(BigDecimal.ZERO);
            }
            return orderInnerDrug;
        }).collect(Collectors.toList());

        orderDetailResp.setDrug(orderInnerDrugList);

        //优惠劵信息
        CouponRespS couponRespS = couponMapper.findUsedCouponInfo(orderTable.getUserInnerCouponId());
        orderDetailResp.setCouponRespS(couponRespS);
        // 总店分店
        if (orderDetailReq.getType() == 1) {
            // 处理用药人
            OrderDrugUsers orderDrugUsers = orderDrugUsersMapper.selectOne(new LambdaQueryWrapper<OrderDrugUsers>().eq(OrderDrugUsers::getOrderId, orderDetailResp.getId()));
            if (ObjectUtil.isNotNull(orderDrugUsers)) {
                orderDetailResp.setDrugUsers(orderDrugUsers);
            }
            //处理售后订单信息
            if (orderDetailResp.getAfterSalesOrNot().equals(Boolean.TRUE)) {
                OrderAfterSales orderAfterSales = orderAfterSalesMapper.selectOne(new LambdaQueryWrapper<OrderAfterSales>().eq(OrderAfterSales::getOrderId, orderDetailResp.getId()));
                orderDetailResp.setOrderAfterSales(orderAfterSales);
            }

        }
        return orderDetailResp;
    }
}
